// index.js
let Moment = require("../../utils/moment.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    message:['http://hotel.ttt/first_show/s1.jpg',
    'http://hotel.ttt/first_show/s2.jpg',
    'http://hotel.ttt/first_show/s3.jpg',
    'http://hotel.ttt/first_show/s4.jpg',
    'http://hotel.ttt/first_show/s5.jpg',
    'http://hotel.ttt/first_show/s6.jpg',
    'http://hotel.ttt/first_show/s7.jpg',
    'http://hotel.ttt/first_show/s8.jpg',],
    checkInDate:new Date().getMonth() + 1+'-'+new Date().getDate(),
    checkOutDate:Moment(new Date()).add(1, 'day').format('MM-DD'),
    stay: 1 ,
    token:'',
    roomMessage:[] , //房间信息
    selBtn:'',//按钮类别
    isPopupVisible: false,
    price:0, //预定几晚的总价
    orderMessage:[],
    checklist:[]
  },
  toseldata:function () { //日期页面跳转
    wx.navigateTo({
      url:'/pageA/pages/date/date',
    })
  },
  getDaysBetween(inDate,outDate){ //一共住几天
    let startDate = Date.parse(inDate);
    let endDate = Date.parse(outDate);
    let days=(endDate - startDate)/(1*24*60*60*1000);
    return  days;
  },

  getroomMessage:function () { //获取房间信息
    var that =this
    wx.request({
      url: 'http://hotel.ttt:3007/api/room',
      method:'GET',
      success:function (res) {
        console.log(res.data.data)
        that.setData({
          roomMessage:res.data.data
        })
      }
    })
  },
  btn1:function () {
    this.setData({
      selBtn:this.data.roomMessage[0].room_type
    })
  },
  btn2:function () {
    this.setData({
      selBtn:this.data.roomMessage[1].room_type
    })
  },
  btn3:function () {
    this.setData({
      selBtn:this.data.roomMessage[2].room_type
    })
  },
  btn4:function () {
    this.setData({
      selBtn:''
    })
  },
  goToMessage(e) {
    let room_id=e.currentTarget.dataset.roomid
    wx.navigateTo({
      url: '/pageA/pages/message/message?room_id='+ room_id+'&stay='+this.data.stay // 新页面路径
    });
  },
  gotoBook:function (e) {
    var that=this
    const token=wx.getStorageSync('token')
    console.log(token)
    if(!token){
      wx.showModal({
        title: '提示',
        content: '请先登录！',
        success(res) {
          if (res.confirm) {
            // 跳转到登录页面
            wx.switchTab({
              url: '/pages/me/me',
            })
          }
        }
      })
    }else{
    let message1=e.currentTarget.dataset
    const res=that.data.roomMessage.find((r)=>r.room_id === message1.id)
    console.log(message1,that.data.roomMessage,res.price);
    that.setData({
      price:res.price*that.data.stay
    })
    wx.navigateTo({
      url: '/pageB/pages/book/book?room_id='+message1.id+'&room_name='+ decodeURIComponent(message1.name)+'&price='+that.data.price
    })
  }
  },

  // 格式化日期函数：将 Date 对象格式化为 'YYYY-MM-DD HH:mm:ss' 格式
 formatDate:function(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
},
// 自定义函数：将 UTC 时间转为中国时间（UTC+8）
  convertToChinaTime:function(utcTime) {
    const date = new Date(utcTime);
    date.setHours(date.getHours() + 8); // 调整时区为 UTC+8（中国标准时间）
    return this.formatDate(date);
  },
  orderMessage:function(){
    var that =this
    wx.request({
      url: 'http://hotel.ttt:3007/api/orderMessage',
      method:'GET',
      success:function (res) {
        console.log(res.data.data)
        that.setData({
          orderMessage:res.data.data
        })
        var checklist=[];
        res.data.data.forEach((item)=>{
          checklist.push(that.convertToChinaTime(item.check_in_date).substring(0,10),that.convertToChinaTime(item.check_out_date).substring(0,10),item.room_id,item.order_id)
        })
        that.setData({
         checklist
        })
      console.log('订单日期和id',checklist)
      that.releaseRoom()
      },
      fail:function(err){
      console.log(err)
      }
    })
  },
  updataRoomStatus:function(status,room_id){
    wx.request({
      url: `http://hotel.ttt:3007/api/usedRoom/${status}/${room_id}`,
      method: 'post',  // 请求方法是 GET
      success:function(res){
        if(res.data.success) console.log('更新房间状态成功');
        else console.log('更新房间状态失败');
      },fail:function(err){
        console.log(err);
      }
    })
  },

  /* calculateTimeDifference() {   //预留房间  释放房间
    var that =this
    // 获取当前时间
    const currentTime = new Date();
    console.log("currentTime:",currentTime)
    // 计算明天0点0分的时间
    const midnight = new Date();
    midnight.setHours(24, 0, 0, 0); // 设置为明天的0点0分0秒
    // 计算时间差（单位：秒）
    const tomorrSeconds = Math.floor((midnight - currentTime) / 1000);
    //到已预定的日期还剩多少秒
    if(!that.data.orderMessage.length){
      console.log('无数据')
      for(var i=1;i<=6;i++){
        that.updataRoomStatus('available',i)
      }
    }else{
      console.log('有数据')
      for(var i=0;i<that.data.orderMessage.length;i++){
        const targetDate = new Date();
        targetDate.setMonth(that.data.checkInMonth[i]-1); // 月份从 0 开始，所以 10 是 11 月
        targetDate.setDate(that.data.checkInDay[i]);  // 设置为 22 号
        targetDate.setHours(0, 0, 0, 0); // 设置为 0 点 0 分 0 秒
        console.log("targetDate:",targetDate)
        // 计算时间差（单位：秒）
        const diffInSeconds = Math.floor((targetDate - currentTime) / 1000); //今天到已预定日期还剩的秒数 
        const shengSeconds=tomorrSeconds+that.data.stay*86400  //今天到明天的时间+需要预定的天数*24h
        const bigtime=diffInSeconds-86400 //最大可容纳的秒数
        console.log("diffInSeconds:",diffInSeconds,"最大可容纳的秒数bigtime:",bigtime,"需要的秒数shengSeconds:",shengSeconds,shengSeconds<bigtime)
        if(shengSeconds<bigtime){
          console.log("房间更新为可用")
          that.updataRoomStatus('available',that.data.checkroom_id[i])
        }
      }
    }
    
  }, */
 isDateInRange:function(InDate,OutDate,startDate, endDate) {
    // 将输入的日期转换为 Date 对象，确保比较的对象是 Date 类型
    const In = new Date(InDate);
    const Out = new Date(OutDate) ;
    const start = new Date(startDate);
    const end = new Date(endDate);
    console.log(InDate,OutDate,startDate, endDate)
    // 判断目标日期是否在开始日期和结束日期之间（包括起始和结束日期）
    if(In>=start&&In<end)return false
    if(Out>start&&Out<=end)return false
    if(Out<=start)return true
    if(In>=end)return true
  },
  completedOrder:function(order_id){
    wx.request({
      url: 'http://hotel.ttt:3007/api/completedOrder',
      method:'POST',
      data:{
        order_status:'completed', 
        order_id:order_id
      },
      success:function(res){
        if(res.data.success)console.log('订单修改已完成状态成功')
        else console.log(res.data)
      },fail:function(err){console.log(err)}
    })
  },
  releaseRoom:function(){
    var ddd=wx.getStorageSync('ROOM_SOURCE_DATE')
    var that=this
    if(that.data.checklist.length===0){
      that.updataRoomStatus('available',0)
    }else{
    console.log('1',that.data.checklist.length)
    for(var i=0 ;i<that.data.checklist.length ;i++){
      const result1 =that.isDateInRange(ddd.checkInDate,ddd.checkOutDate, that.data.checklist[i], that.data.checklist[i+1]);
      console.log("checkInDate:",ddd.checkInDate,"checkOutDate:",ddd.checkOutDate)
      console.log(result1,"true表示不在订单表预定区间内",that.data.checklist[i], that.data.checklist[i+1])
      if(result1){that.updataRoomStatus('available',that.data.checklist[i+2])}
      else{that.updataRoomStatus('booked',that.data.checklist[i+2])}
      const currentTime = new Date();
      const outDate=new Date(that.data.checklist[i+1])
      outDate.setHours(0, 0, 0, 0); // 设置为 0 点 0 分 0 秒
      console.log(currentTime,outDate,currentTime>outDate)
      if(currentTime>outDate){  //自动完成订单
        console.log('订单完成');
        that.completedOrder(that.data.checklist[i+3])
        that.updataRoomStatus('available',that.data.checklist[i+2])
      }
      i=i+3
    }
  }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let ddd=wx.getStorageSync('ROOM_SOURCE_DATE')
    if(ddd){
      console.log(ddd)
      var stay = this.getDaysBetween(ddd.checkInDate, ddd.checkOutDate)  
      this.setData({
        checkInDate:ddd.checkInDate?.substr(5, 5),
        checkOutDate:ddd.checkOutDate?.substr(5, 5),
        stay:stay
      })
      console.log(this.data.checkInDate,this.data.checkOutDate,stay)
    }
    this.getroomMessage()
    this.orderMessage()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})
